package com.starbaba.user.setinfo.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.dictionary.IServiceType;
import com.starbaba.model.utils.HttpConnectionUtils;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.user.setinfo.model.UserInfoSetModel;
import com.starbaba.util.PhoneOrderUtil;
import com.starbaba.utils.TaskExecutor;

@SuppressWarnings({"deprecation", "rawtypes"})
@Component
public class UserInfoSetService {

	private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private static final SimpleDateFormat FULL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public void showPage(Map<String, Object> paramsMap) throws Exception{
		
		List<UserInfoSetModel> activityList = dao.list("select a.activity_id activity_id, b.name activity_name from loan_handphone_record a, loan_product_info b where a.activity_id = b.id group by a.activity_id ", UserInfoSetModel.class);
		paramsMap.put("activityList", activityList);
		
	}
	
	public List<UserInfoSetModel> getList(Integer start, Integer length, PageResponse pageResponse, Map<String, Object> paramsMap) throws Exception {
		
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String activity = (String) paramsMap.get("activity");
		String phone = (String) paramsMap.get("phone");
		String status = (String) paramsMap.get("status");// 领奖资格
		String isfail = (String) paramsMap.get("isfail");
		String isrechar = (String) paramsMap.get("isrechar");
		
		StringBuilder whereParams = new StringBuilder();
		if (StringUtils.isNotEmpty(startTime)) {
			whereParams.append("and a.utime >= '" + startTime + "' ");
		}
		if (StringUtils.isNotEmpty(endTime)) {
			whereParams.append("and a.utime <= '" + endTime + "' ");
		}
		if (StringUtils.isNotEmpty(activity)) {
			whereParams.append("and a.activity_id = '" + activity + "' ");
		}
		if (StringUtils.isNotEmpty(phone)) {
			whereParams.append("and a.mobnum = '" + phone + "' ");
		}
		if (StringUtils.isNotEmpty(status)) {
			if ("1".equals(status)) {
				// 有资格
				whereParams.append("and b.apply_date <= a.utime and a.utime <= DATE_ADD(b.apply_date, INTERVAL 7 DAY) ");
			} else {
				// 没有资格
				whereParams.append("and b.apply_date > a.utime or a.utime > DATE_ADD(b.apply_date, INTERVAL 7 DAY) or b.apply_date is null ");
			}
		}
		if (StringUtils.isNotEmpty(isfail)) {
			// 1 - 可以再次充值   0 - 不可以再次充值
			if ("1".equals(isfail)) {
				whereParams.append("and d.state in ('4','5','9') ");
			}
		}
		if (StringUtils.isNotEmpty(isrechar) && "1".equals(isrechar)) {
			whereParams.append("AND d.state IS NULL ");
			whereParams.append("and b.apply_date <= a.utime and a.utime <= DATE_ADD(b.apply_date, INTERVAL 7 DAY) ");
		} 
		
		StringBuilder listSql = new StringBuilder();
		listSql.append("select a.id id, c.name activity_name, a.mobnum mobnum, a.utime utime, MAX(b.apply_date) apply_date, a.amount amount, ");
		listSql.append("(case when d.state is null then '-1' else d.state end) as money_status ");
		listSql.append("from loan_handphone_record a left join input_userdata b on a.activity_id = b.activity_id and a.mobnum = b.phone ");
		listSql.append("LEFT JOIN loan_product_info c ON a.activity_id = c.id ");
		listSql.append("LEFT OUTER JOIN handphone_order d on a.id = d.orderid and a.mobnum = d.phone_number where 1=1 ");
		listSql.append(whereParams).append(" group by a.id ").append("order by a.utime desc ");
		
		String sqlCount = "select count(1) from (" + listSql.toString() + ") z ";
		
		if (start != null && length != null) {
			listSql.append("limit " + start + ", " + length);
		}
		
		List<UserInfoSetModel> list = dao.list(listSql.toString(), UserInfoSetModel.class);
		for (UserInfoSetModel model : list) {
			
			if (StringUtils.isEmpty(model.getApply_date())) {
				model.setComp("否");
				model.setApply_date("--");
			} else {
				String apData7 = FULL_DATE_FORMAT.format(DateUtils.addDays(FULL_DATE_FORMAT.parse(model.getApply_date()), 7));
				if ((compareDate(model.getUtime(), model.getApply_date()) != -1) && (compareDate(model.getUtime(), apData7) != 1)) {
					// d1 >= d2 && d1 <= d2 + 7 有资格
					model.setComp("是");
				} else {
					model.setComp("否");
				}
			}
//			UserInfoSetModel temp = dao.get("select state money_status from handphone_order where orderid = ? and service_type = '1' ", UserInfoSetModel.class, model.getId());
//			if (temp == null) {
//				model.setMoney_status("-1");
//			} else {
//				model.setMoney_status(temp.getMoney_status());
//			}
		}
		
		if (null != pageResponse) {
			int count = dao.getInt(sqlCount);
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		}
		
		return list;
		
	}
	
	public String recharge(Map<String, Object> paramsMap) throws Exception {

		String message = "";
		String id = (String) paramsMap.get("id");
		String type = (String) paramsMap.get("ch_type");
		
		String getRecord = "select a.*, b.name activity_name, c.product_id comp from loan_handphone_record a, loan_product_info b, comm_user c "
				+ "where a.activity_id = b.id and a.mobnum = c.mobnum and a.id = ? ";
		
		UserInfoSetModel model = dao.get(getRecord, UserInfoSetModel.class, id);
		if (null == model) {
			message = "找不到用户信息";
			return message;
		}
		
		LogService.info("===微信登记送话费活动===正在为" + model.getMobnum() + "用户充值话费，金额：" + model.getAmount() + "元，订单号：" + model.getId());
		String result = PhoneOrderUtil.rechargePhoneFee(model.getMobnum(), Integer.parseInt(model.getAmount()), Long.valueOf(id), IServiceType.XMILES_MANAGER, "1", "送钱活动人工话费充值", null);
		if (JSONUtils.isGoodJson(result)) {
			int r = JSONUtils.parseResult(result);
			JsonObject object = JSONUtils.toJsonObject(result);
			JsonObject e = JSONUtils.toJsonObject(object.get("result"));
			String msg = JSONUtils.checkAsString(e, "msg");
			if (r == 1) {
				message = "订单提交成功，请等待充值结果";
				LogService.info("===微信登记送话费活动===订单提交成功，请等待充值结果");
				// 发短信通知用户话费已经充值
				if (StringUtils.isEmpty(type)) {
					String mobile = model.getMobnum();
					String content = "恭喜您已获得" + model.getActivity_name() + "活动的申请返现金奖励！" + model.getAmount() + "元话费已为您充值，具体到账时间以运营商通知为准。";
					String memo = "送钱活动导入数据充值话费成功提示短信";
					String pid = model.getComp();
					send(mobile, content, memo, 1, Integer.parseInt(pid), null, 0);
				} 
				
			} else {
				message = "充值失败, " + msg;
				LogService.info("===微信登记送话费活动===充值失败, " + msg);
			}
		}
		return message;
		
	}
	
	private static int compareDate(String date1,String date2) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(format.parse(date1));
		Date d1 = calendar.getTime();
		calendar.setTime(format.parse(date2));
		Date d2 = calendar.getTime();
		return d1.compareTo(d2); // d1 < d2  返回 -1 , d1 > d2 返回 1 , d1 = d2 返回 0
	}
	
	private static void send(final String mobileNum, final String content, final String memo,
			final int limit, final int product, final String ip, final int code) {
		TaskExecutor.getInstance().execute(new Runnable() {
			@Override
			public void run() {
				try {
					JsonObject obj = new JsonObject();
					obj.add("phead", new JsonObject());
					obj.addProperty("mobileNum", mobileNum);
					obj.addProperty("content", content);
					obj.addProperty("memo", memo);
					obj.addProperty("limit", limit);
					obj.addProperty("product", product);
					obj.addProperty("ip", ip);
					obj.addProperty("code", code);
					ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
					list.add(new BasicNameValuePair("data", obj.toString()));
					list.add(new BasicNameValuePair("shandle", "0"));
					String response = HttpConnectionUtils.connection(
							Constant.COMMON_HOST
									+ "/loan_utils/common?funid=1&rd="
									+ System.currentTimeMillis(),
							HttpConnectionUtils.POST, list);
					
					LogService.info("===微信登记送话费活动===手动充值短信提醒，send phone:" + mobileNum + ", content:"
							+ content + ", product:" + product + ", response:"
							+ response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public String exportCVS(Map<String, Object> paramsMap) throws Exception {

		// 话费充值状态未处理
		List<UserInfoSetModel> list = this.getList(null, null, null, paramsMap);
		
		StringBuilder builder = new StringBuilder();
		builder.append("活动名称,手机号,登记时间,甲方申请时间,领奖资格,充值金额,话费充值状态\r\n");
		for (UserInfoSetModel vo : list) {
			builder.append(vo.getActivity_name()).append(",");
			builder.append(vo.getMobnum()).append(",");
			builder.append(vo.getUtime()).append(",");
			builder.append(vo.getApply_date()).append(",");
			builder.append(vo.getComp()).append(",");
			builder.append(vo.getAmount()).append(",");
			switch (vo.getMoney_status()) {
				case "-1" :
					builder.append("订单不存在").append(",");
					break;
				case "0" :
					builder.append("充值中").append(",");
					break;
				case "1" :
					builder.append("充值成功").append(",");
					break;
				case "2" :
					builder.append("订单提交失败").append(",");
					break;
				case "3" :
					builder.append("初始化订单").append(",");
					break;
				case "4" :
					builder.append("部分订单提交失败").append(",");
					break;
				case "5" :
					builder.append("部分订单充值失败").append(",");
					break;
				case "9" :
					builder.append("充值失败").append(",");
					break;
				default :
					builder.append("未知").append(",");
					break;
			}
			builder.append("\r\n");
		}
		return builder.toString();
	}
	
}
